package com.itranswarp.javapractice.plugin.data;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GitNode extends Node {

	private static final String URL_BASE = "https://www.liaoxuefeng.com/wiki/1252599548343744";

	private static final Pattern NAME_PATTERN = Pattern.compile("^(\\d+)\\.(.*)\\.(\\d+)$");

	private String path;

	private String mode;

	private String type;

	private String sha;

	private String url;

	private List<Node> children = new ArrayList<>();

	private String name;

	private int index;

	private String displayName;

	private String browserUrl;

	public GitNode init() {
		int n = this.path.lastIndexOf('/');
		this.name = n >= 0 ? this.path.substring(n + 1) : this.path;
		Matcher m = NAME_PATTERN.matcher(this.name);
		if (m.matches()) {
			this.index = Integer.parseInt(m.group(1));
			this.displayName = m.group(2);
			this.browserUrl = URL_BASE + "/" + m.group(3);
		} else {
			this.displayName = this.name;
			this.browserUrl = null;
		}
		if (this.name.equals("Java教程")) {
			this.browserUrl = URL_BASE;
		}
		return this;
	}

	public boolean isPractice() {
		return "blob".equals(this.type) && this.path.endsWith(".zip");
	}

	@Override
	public String getDisplayName() {
		return this.displayName;
	}

	public String getBrowerUrl() {
		return this.browserUrl;
	}

	@Override
	public List<Node> getChildren() {
		return this.children;
	}

	public void addChild(GitNode node) {
		if (this.isParentOf(node)) {
			node.setParent(this);
			this.children.add(node);
			Collections.sort(this.children, (n1, n2) -> {
				return Integer.compare(((GitNode) n1).index, ((GitNode) n2).index);
			});
		} else {
			children.forEach(c -> ((GitNode) c).addChild(node));
		}
	}

	public boolean isParentOf(GitNode node) {
		return node.path.equals(this.path + "/" + node.name);
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getMode() {
		return mode;
	}

	public void setMode(String mode) {
		this.mode = mode;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getSha() {
		return sha;
	}

	public void setSha(String sha) {
		this.sha = sha;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	@Override
	public String toString() {
		return String.format("{GitNode: %s}", this.getDisplayName());
	}

	public String toString(int indent) {
		StringBuilder sb = new StringBuilder(1024);
		for (int i = 0; i < indent; i++) {
			sb.append("  ");
		}
		sb.append(this.getDisplayName());
		if (this.getBrowerUrl() != null) {
			sb.append(" [").append(this.getBrowerUrl()).append("]");
		}
		sb.append('\n');
		this.children.forEach(c -> sb.append(((GitNode) c).toString(indent + 1)));
		return sb.toString();
	}
}
